import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import FuncFormatter


# Define a formatting function to convert numbers to strings with thousand separators

def format_x(x, pos):
    return f'{x:,.0f}'
    # return f"${x:,.0f}"


# Read the CSV file, using the first row as the header
df = pd.read_csv('sensitivity_table-副本.csv',
                 thousands=',', decimal='.', header=0)
# Select columns 1 and 2 for the x and y axes
x = df['Unit PLCP/day [$]']
y = df['Unit PLCP/day [$]']
# Select columns 2, 21, 25, and 26 as dependent variables
ratio_CLAP_PLCP = df.iloc[:, 2]  # Column 2: Ratio of unit CLAP to unit PLCP
avg_TAC_BS = df.iloc[:, 3]  # Column 3: avg. TAC of base schedule[$]
avg_CLAP_BS = df.iloc[:, 4]  # Column 4: avg. CLAP[$]
avg_PLCP_BS = df.iloc[:, 6]  # Column 6: avg. PLCP[$]
avg_suggested_postponement = df.iloc[:, 7]  # Column 7: avg. suggested postponement[day]
avg_TAC_OS = df.iloc[:, 8]  # Column 8: avg. TAC of O.S.[$]
avg_CLAP = df.iloc[:, 9]  # Column 9: avg. CLAP[$]
avg_PLCP = df.iloc[:, 11]  # Column 11: avg. PLCP[$]
reduction_rate = df.iloc[:, 12]
# Set the figure size
# plt.figure(figsize=(15, 5))
# # Create a 1x1 subplot grid with shared x and y axes
# fig, axs = plt.subplots(1, 1, sharex=True, sharey=True)

# ax2 = axs.twinx()
# Define legend labels
legend_labels = [
    # 'Unit CLAP/day [$]',
    # 'Unit PLCP/day [$]',
    'Ratio of unit PLCP to unit CLAP',
    'Avg. TAC of B.S. [$]',
    'Avg. CLAP of B.S. [$]',
    # 'Avg. CLDP of B.S. [$]',
    'Avg. PLCP of B.S. [$]',
    # 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    'Avg. suggested postponement [day]',
    'Avg. TAC of O.S. [$]',
    'Avg. CLAP of O.S. [$]',
    # 'Avg. optimized CLDP [$]',
    'Avg. PLCP of O.S. [$]',
    'Reduction rate'
]

# Plot the cost data of base schedule
for i in range(0, 3, 1):
    line_no = 1
    # Initialize legend handles
    legend_handles = []
    # Set the figure size
    plt.figure(figsize=(25, 10))
    # Create a 1x1 subplot grid with shared x and y axes
    fig, ax1 = plt.subplots(1, 1, sharex=True, sharey=True)
    # ax1.set_ylabel('Ratio of unit PLCP to unit CLAP')

    # ax2 = ax1.twinx()
    ax1.set_ylabel('Additional cost[$]')

    unit_CLAP = df.iloc[i * 3, 0]
    unit_CLAP_str = format_x(unit_CLAP, 4)
    ax1.set_title('Unit CLAP[$]/day=' + unit_CLAP_str)

    # Plot 'Ratio of unit PLCP to unit CLAP'
    # line, = ax1.plot(y[i * 3: i * 3 + 3], ratio_CLAP_PLCP[i * 3: i * 3 + 3],
    #                  marker='^', linestyle='solid', color='red',
    #                  label=legend_labels[0])
    # # line_no += 1
    # legend_handles.append(line)
    # Plot 'Avg. TAC of base schedule[$]'
    line, = ax1.plot(y[i * 3: i * 3 + 3], avg_TAC_BS[i * 3: i * 3 + 3],
                     marker='^',
                     linestyle='solid', linewidth=3, color='orange',
                     label=legend_labels[1])
    # line_no += 1
    legend_handles.append(line)
    # Plot 'avg_CLAP_BS' dashed line
    line, = ax1.plot(y[i * 3: i * 3 + 3], avg_CLAP_BS[i * 3: i * 3 + 3],
                     # marker='s',
                     linestyle='dashed', linewidth=3, color='black',
                     label=legend_labels[2])
    # line_no += 1
    legend_handles.append(line)
    # Plot 'avg_PLCP_BS' dot-dashed line
    line, = ax1.plot(y[i * 3: i * 3 + 3], avg_PLCP_BS[i * 3: i * 3 + 3],
                     marker='d',
                     linestyle=(0, (3, 10, 1, 10)), linewidth=3,
                     color='green',
                     label=legend_labels[3])
    # line_no += 1
    legend_handles.append(line)

    # Add a legend to the plot

    if unit_CLAP == 500:
        # loc_str = "center left"
        loc_str = 'upper left'
        ax1.legend(handles=legend_handles, loc=loc_str)
        # fail to hide the y axis
        # plt.gca().spines['right'].set_visible(False)
        ax1.set_xlabel(' ')
    elif unit_CLAP == 1000:
        # fail to hide the axes
        # ax1.spines['left'].set_visible(False)
        # ax1.spines['right'].set_visible(False)
        # ax1.text(0.50, 0.008, 'Unit PLCP/day [$]', ha='center')
        pass
    else:
        # ax1.spines['left'].set_visible(False)
        ax1.set_xlabel(' ')
    # Adjust the spacing between subplots
    plt.tight_layout()
    ax1.set_xlabel('Unit PLCP/day [$]')

    # Create a FuncFormatter object and pass the formatting function
    formatter = FuncFormatter(format_x)

    # Apply the formatter to the x and y axis tick labels
    plt.gca().xaxis.set_major_formatter(formatter)
    plt.gca().yaxis.set_major_formatter(formatter)

    # set max of ylim of ax1 to max of [z1, z3]
    # ax1.set_ylim(0, max(map(max, [ratio_CLAP_PLCP])))
    # # set max of ylim to max of ax2 to [z2, z4,z5,z6]s
    ax1.set_ylim(0, max(map(max, [avg_TAC_BS, avg_CLAP_BS, avg_CLAP_BS])))
    # set_xticks by either ax
    ax1.set_xticks(y[0:3])
    # Save the plot with a filename that includes the value of CLAP_str
    plt.savefig(f'd:\\sensitivity_analysis_CLAP_BS{unit_CLAP_str}')

    # Display the plot on the screen
    plt.show()
    ax1.cla()
    # ax2.cla()

# optimized schedule
for i in range(2, -1, -1):
    line_no = 1
    # Initialize legend handles
    legend_handles = []
    # Set the figure size
    plt.figure(figsize=(25, 10))
    # Create a 1x1 subplot grid with shared x and y axes
    fig, ax1 = plt.subplots(1, 1, sharex=False, sharey=False)
    # ylabel = "Ratio of unit PLCP to unit CLAP\nAvg. suggested postponement[day]"
    ylabel = "Avg. suggested postponement[day]"
    ax1.set_ylabel(ylabel)

    ax2 = ax1.twinx()
    ax2.set_ylabel("Additional cost[$]")

    unit_CLAP = df.iloc[i * 3, 0]
    unit_CLAP_str = format_x(unit_CLAP, 4)
    ax1.set_title("Unit CLAP[$]/day=" + unit_CLAP_str)

    # Plot 'Ratio of unit PLCP to unit CLAP'
    # line, = ax1.plot(y[i * 3: i * 3 + 3], ratio_CLAP_PLCP[i * 3: i * 3 + 3], marker='^', linestyle='solid', color='red',
    #                  label=legend_labels[0])
    # # line_no += 1
    # legend_handles.append(line)

    # Plot 'Avg. TAC of base schedule[$]'
    # line, = ax2.plot(y[i * 3: i * 3 + 3], avg_TAC_BS[i * 3: i * 3 + 3], marker='v', linestyle='dashdot', color='orange',
    #                  label=legend_labels[1])
    # # line_no += 1
    # legend_handles.append(line)
    # Plot 'Avg. suggested postponement[day]'
    # Plot 'Avg. TAC of base schedule[$] with dash-dotted'
    line, = ax2.plot(y[i * 3: i * 3 + 3], avg_TAC_BS[i * 3: i * 3 + 3],
                     marker='^',
                     linestyle='solid', linewidth=3, color='orange',
                     label='Avg. TAC of B.S. [$]')
    # str(line_no) + "." +
    # legend_labels[1]
    # line_no += 1
    legend_handles.append(line)

    line, = ax1.plot(y[i * 3: i * 3 + 3], avg_suggested_postponement[i * 3: i * 3 + 3],
                     # linestyle=(0, (1, 10)), color='red',
                     # marker='*',
                     linestyle='dotted', color='red',
                     label=legend_labels[4])
    # line_no += 1
    legend_handles.append(line)
    # Plot 'Avg. TAC of O.S.[$]'
    line, = ax2.plot(y[i * 3: i * 3 + 3], avg_TAC_OS[i * 3: i * 3 + 3],
                     marker='s',
                     linestyle='solid', linewidth=3, color='orange',

                     # linestyle=(0, (3, 10, 1, 10)),
                     # color='green',
                     # label=legend_labels[5]
                     label='Avg. TAC of O.S. [$]'
                     )
    # line_no += 1
    legend_handles.append(line)

    # Plot 'Avg. CLAP[$]'
    line, = ax2.plot(y[i * 3: i * 3 + 3], avg_CLAP[i * 3: i * 3 + 3],
                     # marker='s',
                     linestyle='dashed', linewidth=3, color='black',
                     # marker='o', linestyle='dashed', color='blue',
                     label=legend_labels[6])
    # line_no += 1
    legend_handles.append(line)

    # Plot 'Avg. PLCP[$]'
    line, = ax2.plot(y[i * 3: i * 3 + 3], avg_PLCP[i * 3: i * 3 + 3],
                     marker='d',
                     linestyle=(0, (3, 10, 1, 10)),
                     linewidth=3, color='green',

                     # marker='+', linestyle='dotted', color='purple',
                     label=legend_labels[7])
    # line_no += 1
    legend_handles.append(line)

    # Plot 'Reduction rate'
    # line, = ax1.plot(y[i * 3: i * 3 + 3], reduction_rate[i * 3: i * 3 + 3], marker='*', linestyle='dotted', color='yellow',
    #                  label=legend_labels[8])
    # # line_no += 1
    # legend_handles.append(line)

    if unit_CLAP == 500:
        # loc_str = "center left"
        loc_str = 'upper right'
        ax1.legend(handles=legend_handles, loc=loc_str)
        # fail to hide the y axis
        # plt.gca().spines['right'].set_visible(False)
        # ax1.set_xlabel(' ')
    elif unit_CLAP == 1000:
        pass
        # fail to hide the axes
        # ax1.spines['left'].set_visible(False)
        # ax1.spines['right'].set_visible(False)
        # Add a legend to the plot
        # Set global x and y axis labels
        # ax1.set_xlabel('Unit PLCP/day [$]')
        # fig.text(0.50, 0.008, 'Unit PLCP/day [$]', ha='center')
    else:
        pass
        # ax1.spines['left'].set_visible(False)
        # ax1.set_xlabel(' ')
        # Adjust the spacing between subplots
    ax1.set_xlabel('Unit PLCP/day [$]')

    # Adjust the spacing between subplots
    plt.tight_layout()

    # Create a FuncFormatter object and pass the formatting function
    formatter = FuncFormatter(format_x)

    # Apply the formatter to the x and y axis tick labels
    plt.gca().xaxis.set_major_formatter(formatter)
    plt.gca().yaxis.set_major_formatter(formatter)

    # set max of ylim of ax1 to max of [z1, z3]
    # ax1.set_ylim(0, max(map(max, [ratio_CLAP_PLCP, avg_suggested_postponement])))
    ax1.set_ylim(0, max(map(max, [avg_suggested_postponement])))
    # # set max of ylim to max of ax2 to [z2, z4,z5,z6]
    ax2.set_ylim(0, max(map(max, [avg_TAC_BS, avg_TAC_OS, avg_CLAP, avg_PLCP])))
    # set_xticks by either ax
    ax1.set_xticks(y[0:3])
    # Save the plot with a filename that includes the value of CLAP_str
    plt.savefig(f'd:\\sensitivity_analysis_CLAP{unit_CLAP_str}')

    # Display the plot on the screen
    plt.show()
    ax1.cla()
    ax2.cla()
